package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/*
服务端的练习和完善，
 */
public class ServerPlus4 {

    private  List<PrintWriter> allOut = new ArrayList<>();
    private ServerSocket serverSocket;

    public ServerPlus4(){
        try {
            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try{
            while (true) {
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("连接成功");
                Runnable r = new ClientHandler(socket);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ServerPlus4 sp = new ServerPlus4();
        sp.start();

    }

    private  class ClientHandler implements Runnable{
        private Socket socket;
        private String name;
        public ClientHandler(Socket socket){
            this.socket=socket;
            this.name=socket.getInetAddress().getHostName();
        }
        @Override
        public void run() {

            try {
                //读
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                //原数据返回
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);
                allOut.add(pw);
                String temp;
                while ((temp = br.readLine())!=null){
                    System.out.println(name+":" +temp);
                    //将读取到的消息回复给客户端
                    for (PrintWriter o : allOut){
                        o.println(name+":" +temp);
                    }
                }
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
